function fv = isoBinary3(V,X,s,level,color,alpha_level)
%% Thomas Stevens - Lim Lab
%opened 12/25/12
%Generates transparent isosurface of 3D image
%fv = isoBinary3(V,X,s,level,color,alpha_level)
%Inputs:
%V = 3d matrix
%X = cell array of length dimensions
%level = isosurface level, 1-eps best for binary
%s =  contains microscope calibration in um/px, default 1
%color = default 'red'
%alpha_level = 0<a<1, transparency, default 0.25
%Outputs:
%fv is face-vertex structure
%if empty, use path to display on axes

if nargin<6 || isempty(alpha_level)
    alpha_level = 0.5;
end
if nargin<5 || isempty(color)
    color = 'red';
end
if nargin<4 || isempty(level)
    %level = 1-eps;
    level = [];
end
if nargin<3 || isempty(s)
    s = struct();
    % in pixels
    s.calibX = 1;
    s.calibY = 1;
    s.calibZ = 1;
end
if nargin<2 || isempty(X)
    size_V = size(V);
    x = (0:size_V(1)-1)*s.calibX;
    y = (0:size_V(2)-1)*s.calibY;
    z = (0:size_V(3)-1)*s.calibZ;
else
    x = s.calibX*X{1};
    y = s.calibY*X{2};
    z = s.calibZ*X{3};
end

%plot transparent surface of 3D binary
%pad exterior surface with one layer of zeros
%V = padarray(V,[1 1 1]);

%Faster if take bwperim first for binary
if islogical(V)
    V = bwperim(V);
end

if nargout==0
    %plots on current axes
    if isempty(level)
        p1 = patch(isosurface(y,x,z,V));
    else
        p1 = patch(isosurface(y,x,z,V,level));
    end
    set(p1,'facecolor',color,'edgecolor','none');
    %time is consumed mostly here
    %isonormals(x,y,z,V,p1);
    daspect([1 1 1]);
    axis([min(x) max(x) min(y) max(y) min(z) max(z)])
    view(3); grid on;
    camlight;
    lighting gouraud;
    alpha(alpha_level);
else
    %no plot, but return face-vertex structure
    if isempty(level)
        fv = isosurface(x,y,z,V);
    else
        fv = isosurface(x,y,z,V,level);
    end
end



